package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyy.entity.Activity;
import com.xyy.entity.ActivityRegistration;
import com.xyy.entity.Patient;
import com.xyy.exception.BusinessException;
import com.xyy.mapper.ActivityMapper;
import com.xyy.mapper.ActivityRegistrationMapper;
import com.xyy.mapper.PatientMapper;
import com.xyy.service.ActivityRegistrationService;
import com.xyy.vo.ActivityRegistrationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动报名Service实现类
 */
@Slf4j
@Service
public class ActivityRegistrationServiceImpl implements ActivityRegistrationService {
    
    @Resource
    private ActivityRegistrationMapper registrationMapper;
    
    @Resource
    private ActivityMapper activityMapper;
    
    @Resource
    private PatientMapper patientMapper;
    
    @Override
    @Transactional
    public ActivityRegistrationVO registerActivity(ActivityRegistration registrationDTO, Long userId) {
        // 检查活动是否存在
        Activity activity = activityMapper.selectById(registrationDTO.getActivityId());
        if (activity == null) {
            throw new BusinessException("活动不存在");
        }
        
        // 检查活动是否已结束（根据结束时间判断）
        if (activity.getEndTime() != null && activity.getEndTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("活动已结束，无法报名");
        }
        
        // 检查就诊人是否存在且属于当前用户
        Patient patient = patientMapper.selectById(registrationDTO.getPatientId());
        if (patient == null || !patient.getUserId().equals(userId)) {
            throw new BusinessException("就诊人不存在或无权限");
        }
        
        // 检查是否已报名
        if (isAlreadyRegistered(registrationDTO.getActivityId(), registrationDTO.getPatientId())) {
            throw new BusinessException("该就诊人已报名此活动");
        }
        
        // 创建报名记录
        ActivityRegistration registration = new ActivityRegistration();
        registration.setActivityId(registrationDTO.getActivityId());
        registration.setUserId(userId);
        registration.setPatientId(registrationDTO.getPatientId());
        registration.setStatus("PENDING");
        registration.setRegistrationTime(LocalDateTime.now());
        registration.setRemark(registrationDTO.getRemark());
        
        registrationMapper.insert(registration);
        
        // 返回报名信息
        return getUserRegistrations(userId).stream()
                .filter(vo -> vo.getId().equals(registration.getId()))
                .findFirst()
                .orElse(null);
    }
    
    @Override
    @Transactional
    public boolean cancelRegistration(Long registrationId, Long userId) {
        // 检查报名记录是否存在且属于当前用户
        ActivityRegistration registration = registrationMapper.selectById(registrationId);
        if (registration == null || !registration.getUserId().equals(userId)) {
            return false;
        }
        
        // 检查是否可以取消
        if ("CANCELLED".equals(registration.getStatus())) {
            throw new BusinessException("报名已取消");
        }
        
        if ("CONFIRMED".equals(registration.getStatus())) {
            throw new BusinessException("报名已确认，无法取消");
        }
        
        // 更新状态
        registration.setStatus("CANCELLED");
        registration.setCancelTime(LocalDateTime.now());
        
        return registrationMapper.updateById(registration) > 0;
    }
    
    @Override
    @Transactional
    public boolean confirmRegistration(Long registrationId, Long adminId) {
        // 检查报名记录是否存在
        ActivityRegistration registration = registrationMapper.selectById(registrationId);
        if (registration == null) {
            return false;
        }
        
        // 检查活动是否属于当前管理员
        Activity activity = activityMapper.selectById(registration.getActivityId());
        if (activity == null || !activity.getAdminId().equals(adminId)) {
            return false;
        }
        
        // 检查是否可以确认
        if ("CANCELLED".equals(registration.getStatus())) {
            throw new BusinessException("报名已取消，无法确认");
        }
        
        if ("CONFIRMED".equals(registration.getStatus())) {
            throw new BusinessException("报名已确认");
        }
        
        // 更新状态
        registration.setStatus("CONFIRMED");
        registration.setConfirmTime(LocalDateTime.now());
        
        return registrationMapper.updateById(registration) > 0;
    }
    
    @Override
    public List<ActivityRegistrationVO> getUserRegistrations(Long userId) {
        return registrationMapper.selectRegistrationsByUserId(userId);
    }
    
    @Override
    public List<ActivityRegistrationVO> getActivityRegistrations(Long activityId, Long adminId) {
        // 检查活动是否属于当前管理员
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null || !activity.getAdminId().equals(adminId)) {
            throw new BusinessException("活动不存在或无权限查看");
        }
        
        return registrationMapper.selectRegistrationsByActivityId(activityId);
    }
    
    @Override
    public boolean isAlreadyRegistered(Long activityId, Long patientId) {
        return registrationMapper.checkRegistrationExists(activityId, patientId) > 0;
    }
} 